import {MSG_LIST, MSG_READ, MSG_RECEIVE,ON_SOCKET} from "../actions/chatAction";
import {LOGOUT} from "../actions/userActions";
const initialState = {
    chatMsg: [],
    unread: 0,
    users:[],
    onSocket:false
}


export function chat(state = initialState, action) {
    switch (action.type) {
        case MSG_LIST:
            return {...state,chatMsg:action.payload.msgs,unread:action.payload.msgs.filter(v=>!v.read&&v.to===action.payload.userid).length,users:action.payload.users}
        case MSG_RECEIVE:
            const num=action.payload.userid===action.payload.data.to?1:0
            return {...state,chatMsg:[...state.chatMsg,action.payload.data],unread:state.unread+num}
        case MSG_READ:

            return {...state,chatMsg:state.chatMsg.map(v=>{
                v.read=v.from===action.payload.from?true:v.read
                    return v
                }),unread:state.unread-action.payload.num}
        case ON_SOCKET:
            return{...state,onSocket:action.payload}
        case LOGOUT:
            return {...initialState}
        default:
            return state
    }
}



